//
//  WLMPictureSelectorController.swift
//  WeiBo
//
//  Created by Eric on 2017-01-16.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit

private let pictureSelectorCellId = "pictureSelectorCell"
let selectorCellMargin: CGFloat = 4
private let colCount: CGFloat = 3
let selectorItemWidth: CGFloat = (ScreenWidth - (colCount + 1) * selectorCellMargin) / colCount

private let imagesMaxCount = 4

class WLMPictureSelectorController: UICollectionViewController {

    lazy var images = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(WLMPictureSelectorCell.self, forCellWithReuseIdentifier: pictureSelectorCellId)

    }


    // MARK: UICollectionViewDataSource
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = (images.count == imagesMaxCount ? 0 : 1)
        return images.count + delta
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureSelectorCellId, for: indexPath) as! WLMPictureSelectorCell
    
        if indexPath.item == images.count {
            cell.image = nil
        }
        else {
            cell.image = self.images[indexPath.item]
        }
        cell.delegate = self
    
        return cell
    }
}

extension WLMPictureSelectorController: WLMPictureSelectorCellDelegate{
    func userWillAddPic() {
        let picker = UIImagePickerController()
        picker.delegate = self
        present(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePic(cell: WLMPictureSelectorCell) {
        let indexPath = collectionView?.indexPath(for: cell)
        images.remove(at: indexPath!.item)
        collectionView?.reloadData()
        self.view.isHidden = (images.count == 0)
    }
}

extension WLMPictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = (info[UIImagePickerControllerOriginalImage] as! UIImage).scaleImage(width: 600)
        images.append(image)
        collectionView?.reloadData()
        self.dismiss(animated: true, completion: nil)
    }
    
}
